
import requests
import base64
import json

LanguageMulti = {
    "ru" : 0,#俄语
    "ha":1,
    "yue":2,
    "wei":3,
    "ar":8,#阿语
    "bo":9,#藏语
}
def getresult(filename, language1 = "mn"):
    imgData = open(r"%s" % filename, "rb")
    base64data = str(base64.b64encode(imgData.read()), encoding="utf-8")
    imgData.close()
    body = {'img': base64data, 'language': language1}
    headers = {
        "Content-Type": "application/x-www-form-urlencoded"
    }
    try:
        r = requests.post(
            'http://120.92.70.225:80/hanwang/ocr_image'
            # "http://120.92.70.225/trans/pic/v1/ocr_image"
            , headers=headers, data=body)
    except requests.exceptions.HTTPError as e:
        print(e)
        return
    except requests.exceptions.RequestException as e:
        print(e)
        return
    ocrResult2Json = json.loads(r.content.decode("utf-8"))
    return ocrResult2Json

class OcrImageHw:
    URL = "http://121.36.46.22:80/"
    # http://cloud.hw-ai.com/#/secret
    client_id= "a91-user-fuweiqiang" #输入注册后获取ID
    client_secret="c7d8961ca5e74168b" #输入注册后获取secret

    def connect_new(self, base64_data, language):

        print('language: '+ language)
        #res = {'image': base64_data, 'isAnalysis': 1}
        body = {'img':base64_data, 'language': language}

        headers = {
            "Content-Type": "application/x-www-form-urlencoded"
        }
        r = requests.post('http://120.92.70.225:80/hanwang/ocr_image', headers=headers, data=body)

        print("url request Completed!")
        return r.content

file = "D:\\zang-tab.png"
result_dir = "D:\\"
hwmodel = OcrImageHw()
language = "bo"

def test():
    imgData = open(r"%s" % file, "rb")
    base64data = str(base64.b64encode(imgData.read()), encoding="utf-8")
    response = hwmodel.connect_new(base64data, language)
    imgData.close()
    ocrResult2Json = json.loads(response.decode("utf-8"))
    print(ocrResult2Json)
    recognise_str = ''
    real_value_str = ''
    to_write_file_str = ''
    if 'Paraph' in ocrResult2Json:
        for paraph in ocrResult2Json['Paraph']:
            for line in paraph['line']:
                # recognise_str += ' '
                to_write_file_str += line['code'] + ' '
                recognise_str += line['code'] + ' '
            to_write_file_str += '\n'
    elif 'Table' in ocrResult2Json:
        for table in ocrResult2Json['Table']:
            for cell in table['cell']:
                for paraph in cell['paragh']:
                    for line in paraph['line']:
                        to_write_file_str += line['code'] + ' '
                        recognise_str += line['code'] + ' '
            to_write_file_str += '\n'

    with open(r"%s" % result_dir + "result.txt", 'wb') as f1:
        f1.write(to_write_file_str.encode('utf-8'))

if __name__ == "__main__":
 test()